"""
增强的Photoshop脚本生成器
包含坐标验证和调试功能
"""

def generate_enhanced_photoshop_script(original_psd_path, json_images_info, canvas_width, canvas_height, timestamp, unique_id, export_folder):
    """生成增强的Photoshop脚本，包含坐标验证"""
    
    script_filename = f"enhanced_rebuild_{timestamp}_{unique_id}.jsx"
    script_path = export_folder / script_filename
    
    script_content = f'''// 增强Photoshop图层重建脚本（含坐标验证）
// 生成时间: {timestamp}
// 画布尺寸: {canvas_width} x {canvas_height}

// 设置Photoshop单位为像素
app.preferences.rulerUnits = Units.PIXELS;

// 关闭所有文档
while (app.documents.length > 0) {{
    app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}}

try {{
    // 1. 打开原始PSD文件
    var originalPsdFile = new File("{original_psd_path.as_posix() if original_psd_path else ''}");
    if (!originalPsdFile.exists) {{
        alert("❌ 原始PSD文件不存在: {original_psd_path.name if original_psd_path else 'N/A'}");
        throw new Error("PSD文件不存在");
    }}
    
    var doc = app.open(originalPsdFile);
    app.activeDocument = doc;
    
    // 验证文档尺寸
    var docWidth = doc.width.as('px');
    var docHeight = doc.height.as('px');
    
    alert("✅ 成功打开原始PSD文件\\n" +
          "文档尺寸: " + docWidth + " x " + docHeight + "\\n" +
          "预期尺寸: {canvas_width} x {canvas_height}\\n" +
          "原始图层数: " + doc.layers.length);
    
    // 2. 添加JSON图片
'''
    
    for i, image_info in enumerate(json_images_info):
        user_data = image_info['user_data']
        position = user_data.get('position', {})
        dimension = user_data.get('dimension', {})
        rotation = user_data.get('angle_of_rotation', 0)
        
        target_x = position.get('x', 0)
        target_y = position.get('y', 0)
        target_width = dimension.get('width', image_info['size'][0])
        target_height = dimension.get('height', image_info['size'][1])
        
        script_content += f'''
    // JSON图片 {i+1}: {image_info['filename']}
    try {{
        var jsonImageFile = new File("{image_info['local_path'].replace(chr(92), '/')}");
        if (!jsonImageFile.exists) {{
            alert("❌ JSON图片文件不存在: {image_info['filename']}");
            throw new Error("图片文件不存在");
        }}
        
        // 打开JSON图片
        var jsonDoc = app.open(jsonImageFile);
        var jsonWidth = jsonDoc.width.as('px');
        var jsonHeight = jsonDoc.height.as('px');
        
        // 全选并复制
        jsonDoc.selection.selectAll();
        jsonDoc.selection.copy();
        jsonDoc.close(SaveOptions.DONOTSAVECHANGES);
        
        // 切换回主文档
        app.activeDocument = doc;
        
        // 粘贴为新图层
        var newLayer = doc.paste();
        newLayer.name = "JSON图片_{i+1}_位置({target_x},{target_y})";
        
        // 获取粘贴后的图层边界
        var pastedLeft = newLayer.bounds[0].as('px');
        var pastedTop = newLayer.bounds[1].as('px');
        var pastedWidth = newLayer.bounds[2].as('px') - newLayer.bounds[0].as('px');
        var pastedHeight = newLayer.bounds[3].as('px') - newLayer.bounds[1].as('px');
        
        // 计算移动距离（精确到像素）
        var moveX = {target_x} - pastedLeft;
        var moveY = {target_y} - pastedTop;
        
        // 移动图层到目标位置
        newLayer.translate(UnitValue(moveX, 'px'), UnitValue(moveY, 'px'));
        
        // 验证最终位置
        var finalLeft = newLayer.bounds[0].as('px');
        var finalTop = newLayer.bounds[1].as('px');
        
        // 调整尺寸（如果需要）
        {f'''
        var currentWidth = newLayer.bounds[2].as('px') - newLayer.bounds[0].as('px');
        var currentHeight = newLayer.bounds[3].as('px') - newLayer.bounds[1].as('px');
        var scaleX = ({target_width} / currentWidth) * 100;
        var scaleY = ({target_height} / currentHeight) * 100;
        newLayer.resize(scaleX, scaleY, AnchorPosition.TOPLEFT);
        ''' if target_width != image_info['size'][0] or target_height != image_info['size'][1] else '// 保持原始尺寸'}
        
        // 应用旋转
        {f'newLayer.rotate({rotation}, AnchorPosition.MIDDLECENTER);' if rotation != 0 else '// 无旋转'}
        
        // 显示详细信息
        alert("✅ JSON图片_{i+1} 处理完成\\n\\n" +
              "配置信息:\\n" +
              "- 目标位置: ({target_x}, {target_y})\\n" +
              "- 目标尺寸: {target_width} x {target_height}\\n" +
              "- 旋转角度: {rotation}°\\n\\n" +
              "实际结果:\\n" +
              "- 粘贴位置: (" + pastedLeft + ", " + pastedTop + ")\\n" +
              "- 移动距离: (" + moveX + ", " + moveY + ")\\n" +
              "- 最终位置: (" + finalLeft + ", " + finalTop + ")\\n" +
              "- 原始尺寸: " + jsonWidth + " x " + jsonHeight);
        
    }} catch(e) {{
        alert("❌ 处理JSON图片_{i+1}失败: " + e.message);
    }}
'''
    
    script_content += f'''
    // 完成处理
    alert("🎉 图层重建完成！\\n\\n" +
          "结果统计:\\n" +
          "- 原始图层: 已保留所有PSD图层\\n" +
          "- 新增图层: {len(json_images_info)}个JSON图片\\n" +
          "- 文档尺寸: " + docWidth + " x " + docHeight + "\\n\\n" +
          "现在您可以看到完整的图层结构，所有坐标都已精确对齐！");
          
}} catch(e) {{
    alert("❌ 脚本执行失败: " + e.message + "\\n\\n请检查:\\n1. PSD文件路径是否正确\\n2. JSON图片是否存在\\n3. Photoshop版本兼容性");
}}
'''
    
    with open(script_path, 'w', encoding='utf-8') as f:
        f.write(script_content)
    
    print(f"生成增强PS脚本: {script_path}")
    return script_path
